package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-02-16
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //添加课程分类
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            //文件输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取课程tree
     * @return
     */
    @Override
    public List<EduSubject> getAllSubject() {
        List<EduSubject> list = this.list(null);
        return list.stream().filter(eduSubject -> "0".equals(eduSubject.getParentId()))
                .map(eduSubject -> eduSubject.setChildren(getChildren(eduSubject.getId(), list)))
                .collect(Collectors.toList());
    }

    /**
     * 递归获取子节点（递归找到他的子节点，直到找到最后一个子节点为止，并进行封装。）
     * @param parentId
     * @param subjectList
     * @return
     */
    private List<EduSubject> getChildren(String parentId, List<EduSubject> subjectList){
        return subjectList.stream().filter(eduSubject -> parentId.equals(eduSubject.getParentId()))
                .map(eduSubject -> eduSubject.setChildren(getChildren(eduSubject.getId(), subjectList)))
                .collect(Collectors.toList());
    }
}
